package cn.tedu.boot101.controller;

import cn.tedu.boot101.mapper.CommentMapper;
import cn.tedu.boot101.mapper.WeiboMapper;
import cn.tedu.boot101.pojo.dto.WeiboInsertDto;
import cn.tedu.boot101.pojo.entity.User;
import cn.tedu.boot101.pojo.entity.Weibo;
import cn.tedu.boot101.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo")
public class WeiboController {
    @Autowired
    WeiboMapper mapper;
    @Autowired
    CommentMapper commentMapper;

    @RequestMapping("/insert")
    public int insert(@RequestBody WeiboInsertDto weiboInsertDto, HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return 2;
        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboInsertDto, weibo);
        weibo.setCreated(new Date());
        weibo.setUser_id(user.getId());
        mapper.insert(weibo);
        return 1;
    }

    @RequestMapping("/select")
    public List<WeiboIndexVO> select() {
        return mapper.select();
    }

    @RequestMapping("/selectById")
    public WeiboDetailVO selectById(int id) {
        return mapper.selectById(id);
    }

    @RequestMapping("/selectByUserId")
    public ResultVO selectByUserId(HttpSession session) {
        UserVO user = (UserVO) session.getAttribute("user");
        if (user == null) {
            return new ResultVO(2, "用户未登录！", null);
        }
        return new ResultVO(1, "请求成功", mapper.selectByUserId(user.getId()));
    }

    @RequestMapping("/deleteMyWeibo")
    public void deleteMyWeibo(int id) {
        WeiboDetailVO w = mapper.selectById(id);
        String[] urls = w.getUrls().split(",");
        for (String url : urls) {
            String dirPath = "f:/files";
            new File(dirPath + url).delete();
        }
        mapper.deleteMyWeiboById(id);
        commentMapper.deleteByWeiboId(id);
    }
}
